<template>
  <div class="env_container">
    <div ref="terminalRef"
         style="font-size: 12px; color: #000;">
    </div>
    <!-- <Timeline>
      <TimelineItem v-for="(item, index) in envs"
                    :key="item.name">
        <div class="item_dot"
             slot="dot"
             v-if="currentStep === index || item.installing">
          <img src="http://static.dei2.com/resources/loading.gif"
               alt="">
        </div>
        <Icon v-else
              :type="item.status == 0 ? 'ios-radio-button-off' : (item.status == 1 ? 'ios-checkmark-circle' : 'ios-close-circle')"
              slot="dot"
              :color="item.status == -1 ? '#f33' : (item.status == 1 ? '#19be6b' : '#dcdee2')"
              size="18"></Icon>

        <div class="item_title">
          <div style="display: flex; flex-direction: row; align-items: center;">
            <p v-text="item.name + ' 检测'"></p>
          </div>
          <transition name="fade">
            <a href="javascript:void(0)"
               v-if="!envs[index].installed && !envs[index].installing"
               @click="installDependence(index)"
               v-text="'安装 ' + envs[index].name"></a>
          </transition>
        </div>

        <p class="item_desc"
           v-for="(itm, idx) in item.desc"
           :key="idx"
           v-html="itm"></p>
      </TimelineItem>
    </Timeline> -->
  </div>
</template>

<script>
import { Timeline, TimelineItem, Icon, Spin } from 'view-design'
import "xterm/css/xterm.css"
import { Terminal } from 'xterm'
export default {
  name: "Environment",
  components: {
    Timeline, TimelineItem, Icon, Spin
  },
  data () {
    return {
      envs: [
        {
          name: 'node',
          status: 0,
          desc: [],
          installed: true,
          installing: false,
        },
        {
          name: 'enkel',
          status: 0,
          desc: [],
          installed: true,
          installing: false,
        }
      ],
      currentStep: 0,
      installingText: '安装中...',
      execResult: 'Initialed',
      term: null
    }
  },
  mounted () {
    this.$nextTick(() => {
      setTimeout(() => {
        this.checkExists(this.currentStep)
      }, 1000)
    })



    this.initTerm()

    bbtools.on('shell-exec-response-Test-ID', this.shellExecHandler)

    bbtools.send('shell-exec', {
      id: 'Test-ID',
      script: 'flutter --version'
    })


  },
  beforeDestroy () {
    if (this.term) {
      this.term.dispose()
    }
  },
  methods: {
    initTerm () {
      if (!this.term) {
        this.term = new Terminal({
          disableStdin: false, //是否应禁用输入。
          cursorStyle: "underline", //光标样式
          cursorBlink: true, //光标闪烁
          theme: {
            foreground: "#7e9192", //字体
            background: "#002833", //背景色
            cursor: "help", //设置光标
            lineHeight: 16
          }
        })
        this.term.open(this.$refs.terminalRef)
        // this.term.writeln('Welcome to bbtool shell')
      }

      this.term.prompt = () => {
        this.term.write('\r\nbbt$ ');
      }

      // this.term.prompt()

      let cmd = ''
      this.term.onKey(e => {
        const printable = !e.domEvent.altKey && !e.domEvent.altGraphKey && !e.domEvent.ctrlKey && !e.domEvent.metaKey;

        if (e.domEvent.keyCode === 13) {
          bbtools.send('shell-exec', {
            id: 'Test-ID',
            script: cmd
          })
          cmd = ''
          this.term.prompt()
        } else if (e.domEvent.keyCode === 8) {
          // Do not delete the prompt

          if (this.term._core.buffer.x > 5) {
            cmd = cmd.substring(0, cmd.length - 1)
            this.term.write('\b \b');
          }
        } else if (printable) {
          cmd = cmd + e.key
          this.term.write(e.key);
        }
      });
    },
    shellExecHandler (event, data) {
      if (this.term) {
        this.term.write(data)
      }
    },
    installDependence (index) {
      if (index == 0) {
        bbtools.shell.openExternal('https://nodejs.org/zh-cn/')
      } else if (index == 1) {
        this.envs[index].installing = true
        this.envs[index].desc = [this.installingText]
        const res = bbtools.childProcess.spawn('npm', ['i', 'enkel-server', '-g'], { encoding: 'utf-8' })
        res.stdout.on('data', (data) => {
          if (this.envs[index].desc[0] == this.installingText) {
            this.envs[index].desc[0] = data.toString('utf-8')
          } else {
            this.envs[index].desc.push(data.toString('utf-8'))
          }
        })
        res.stderr.on('data', (data) => {
          this.envs[index].desc.push('安装失败')
        })
        res.on('close', (code) => {
          this.envs[index].installing = false
          if (code == 0) {
            // 安装成功
            this.envs[index].status = 1
            this.envs[index].desc = ['发现 enkel']
            this.envs[index].installed = true
            this.checkVersion(index)
            if (index == this.envs.length) {
              console.log('安装成功1')
            }
          } else {
            // 安装失败
            this.envs[index].desc.splice(1, this.envs[index].length, '安装失败')
            this.envs[index].installed = false
          }
        })
      }
    },
    async checkExists (index) {
      if (index == this.envs.length) {
        console.log('安装成功2')
      }
      if (index >= this.envs.length) {
        return
      }
      bbtools.execa('which', [this.envs[index].name]).then(data => {
        this.envs[index].desc.push('发现 ' + this.envs[index].name)
        this.checkVersion(index)
      }).catch(err => {
        this.currentStep = -1
        this.envs[index].status = -1
        this.envs[index].installed = false
        this.envs[index].desc = ['<span style="color: #f33;">未发现 ' + this.envs[index].name + '</span>']
      })
    },
    async checkVersion (index) {

      if (index >= this.envs.length) {
        return
      }
      bbtools.execa(this.envs[index].name, ['--version'], { encoding: 'utf-8' }).then(data => {
        if (data && data.stdout) {
          this.envs[index].status = 1
          this.envs[index].desc.push('版本号: ' + data.stdout.toString('utf-8').replace(/[\s\r\n]/g, ''))
          if (this.currentStep < this.envs.length) {
            this.currentStep += 1
            this.checkExists(this.currentStep)
          }
        }
      }).catch(err => {
        this.currentStep = -1
        this.envs[index].status = -1
        this.envs[index].desc = ['<span style="color: #f33;">' + err.message + '</span>']
      })
    }
  }
}
</script>

<style lang="less" scoped>
.env_container {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #fff;
  display: flex;
  flex-direction: row;
  padding: 15px;
  box-sizing: border-box;

  .item_dot {
    width: 18px;
    height: 18px;
    margin: 0 auto;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    img {
      max-width: 100%;
      max-height: 100%;
    }
  }
  .item_title {
    font-size: 14px;
    font-weight: bold;
    display: flex;
    flex-direction: row;
    align-items: center;
    a {
      font-size: 12px;
      font-weight: normal;
      margin-left: 8px;
    }
    &_loading {
      height: 16px;
      margin-left: 8px;
      display: flex;
      flex-direction: row;
      align-items: center;

      img {
        max-width: 100%;
        max-height: 100%;
        margin-right: 8px;
      }
      p {
        font-size: 12px;
        color: #888;
      }
    }
  }
  .item_desc {
    padding-left: 5px;
    font-size: 12px;
    line-height: 24px;
    color: #888;
  }

  .demo-spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
  }
  @keyframes ani-demo-spin {
    from {
      transform: rotate(0deg);
    }
    50% {
      transform: rotate(180deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
}
</style>